<template>
  <div class="orders-container">
    <div class="page-header">
      <h2>我的订单</h2>
    </div>

    <el-card class="order-card">
      <el-tabs v-model="activeTab" class="order-tabs">
        <el-tab-pane label="全部订单" name="all">
          <el-table 
            :data="orders" 
            v-loading="loading" 
            style="width: 100%"
            :row-class-name="tableRowClassName"
          >
            <el-table-column prop="ID" label="订单号" width="100" />
            <el-table-column label="订单信息" min-width="300">
              <template #default="{ row }">
                <div class="order-info-cell">
                  <div class="order-items-preview">
                    <template v-for="(item, index) in row.Items" :key="item.ID">
                      <img 
                        :src="item.Dish?.image_url || '/default-dish.jpg'" 
                        class="dish-preview-image"
                        :alt="item.Dish?.name"
                      >
                      <span v-if="index < row.Items.length - 1" class="divider">+</span>
                    </template>
                  </div>
                  <div class="order-brief">
                    <span class="order-time">{{ formatDate(row.CreatedAt) }}</span>
                    <span class="order-count">共 {{ row.Items.length }} 件商品</span>
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="就餐方式" width="120" align="center">
              <template #default="{ row }">
                <el-tag 
                  :type="row.OrderType === 'dine_in' ? 'success' : 'warning'"
                  effect="plain"
                >
                  {{ row.OrderType === 'dine_in' ? '堂食' : '外卖' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="TotalAmount" label="实付金额" width="150" align="center">
              <template #default="{ row }">
                <span class="amount">¥{{ row.TotalAmount.toFixed(2) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="订单状态" width="120" align="center">
              <template #default="{ row }">
                <el-tag 
                  :type="getStatusType(row.Status)"
                  effect="light"
                >
                  {{ getStatusText(row.Status) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="120" align="center">
              <template #default="{ row }">
                <el-button 
                  type="primary" 
                  link
                  @click="showOrderDetail(row)"
                >
                  查看详情
                </el-button>
                <el-button
                  v-if="row.Status === 'completed' && !row.IsReviewed"
                  type="success"
                  link
                  @click="showReviewDialog(row)"
                >
                  评价
                </el-button>
                <el-tag
                  v-else-if="row.Status === 'completed' && row.IsReviewed"
                  type="info"
                  effect="plain"
                  size="small"
                >
                  已评价
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
          
          <!-- 添加分页组件 -->
          <div class="pagination-container">
            <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :page-sizes="[5, 10, 20, 50]"
              :total="total"
              layout="total, sizes, prev, pager, next"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 订单详情对话框 -->
    <el-dialog
      v-model="detailVisible"
      title="订单详情"
      width="700px"
      class="order-detail-dialog"
    >
      <div v-if="currentOrder" class="order-detail">
        <div class="detail-header">
          <div class="status-banner" :class="currentOrder.Status">
            <span class="status-text">{{ getStatusText(currentOrder.Status) }}</span>
          </div>
          <div class="order-info">
            <div class="info-row">
              <div class="info-item">
                <span class="label">订单号：</span>
                <span class="value">{{ currentOrder.ID }}</span>
              </div>
              <div class="info-item">
                <span class="label">下单时间：</span>
                <span class="value">{{ formatDate(currentOrder.CreatedAt) }}</span>
              </div>
            </div>
            <div class="info-row">
              <div class="info-item">
                <span class="label">就餐方式：</span>
                <el-tag 
                  :type="currentOrder.OrderType === 'dine_in' ? 'success' : 'warning'"
                  effect="plain"
                >
                  {{ currentOrder.OrderType === 'dine_in' ? '堂食' : '外卖' }}
                </el-tag>
              </div>
            </div>
            <template v-if="currentOrder.OrderType === 'takeout'">
              <div class="info-row">
                <div class="info-item full-width">
                  <span class="label">配送地址：</span>
                  <span class="value">{{ currentOrder.Address }}</span>
                </div>
              </div>
              <div class="info-row">
                <div class="info-item">
                  <span class="label">联系电话：</span>
                  <span class="value">{{ currentOrder.Phone }}</span>
                </div>
              </div>
            </template>
          </div>
        </div>

        <el-divider>订单明细</el-divider>

        <el-table :data="currentOrder.Items" border class="detail-table">
          <el-table-column label="商品信息" min-width="300">
            <template #default="{ row }">
              <div class="dish-info">
                <img :src="row.Dish?.image_url || '/default-dish.jpg'" class="dish-image">
                <div class="dish-detail">
                  <span class="dish-name">{{ row.Dish?.name }}</span>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="Price" label="单价" width="120" align="center">
            <template #default="{ row }">
              ¥{{ row.Price.toFixed(2) }}
            </template>
          </el-table-column>
          <el-table-column prop="Quantity" label="数量" width="100" align="center" />
          <el-table-column prop="Subtotal" label="小计" width="120" align="right">
            <template #default="{ row }">
              ¥{{ row.Subtotal.toFixed(2) }}
            </template>
          </el-table-column>
        </el-table>

        <div class="order-total">
          <span>订单总额：</span>
          <span class="total-amount">¥{{ currentOrder.TotalAmount.toFixed(2) }}</span>
        </div>

        <!-- 添加评价详情部分 -->
        <div v-if="currentOrder?.Status === 'completed' && currentOrder?.IsReviewed" class="reviews-section">
          <div class="section-title">
            <h3>评价信息</h3>
          </div>
          <div class="reviews-list">
            <div v-for="item in currentOrder.Items" :key="item.ID" class="review-item">
              <div class="dish-info">
                <img :src="item.Dish?.image_url || '/default-dish.jpg'" class="dish-image">
                <span class="dish-name">{{ item.Dish?.name }}</span>
              </div>
              
              <template v-if="item.Review">
                <div class="review-content">
                  <div class="rating-row">
                    <el-rate :model-value="item.Review.Rating" disabled />
                    <span class="review-time">{{ formatDate(item.Review.CreatedAt) }}</span>
                  </div>
                  <p class="review-text">{{ item.Review.Content }}</p>
                  
                  <!-- 评价图片 -->
                  <div v-if="item.Review.Images && item.Review.Images.length > 0 && item.Review.Images !== '[]'" class="review-images">
                    <el-image
                      v-for="img in item.Review.Images"
                      :key="img"
                      :src="img"
                      :preview-src-list="item.Review.Images"
                      style="width: 80px; height: 80px"
                      fit="cover"
                    />
                  </div>
                  
                  <!-- 商家回复 -->
                  <div v-if="item.Review.Reply" class="merchant-reply">
                    <h4>商家回复：</h4>
                    <p>{{ item.Review.Reply }}</p>
                  </div>
                </div>
              </template>
              <template v-else>
                <div class="no-review">
                  <el-button 
                    type="primary" 
                    link 
                    @click="showReviewDialog(currentOrder, item)"
                  >
                    立即评价
                  </el-button>
                </div>
              </template>
            </div>
          </div>
        </div>
        <!-- 未评价时显示评价按钮 -->
        <div v-else-if="currentOrder?.Status === 'completed' && !currentOrder?.IsReviewed" class="no-review-section">
          <el-empty description="暂无评价">
            <el-button type="primary" @click="showReviewDialog(currentOrder)">
              立即评价
            </el-button>
          </el-empty>
        </div>
      </div>
    </el-dialog>

    <!-- 评价对话框 -->
    <el-dialog
      v-model="reviewDialogVisible"
      title="订单评价"
      width="600px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form :model="reviewForm" label-width="80px">
        <div v-for="(item, index) in currentReviewOrder?.Items" :key="item.DishID" class="dish-review-item">
          <div class="dish-info">
            <img :src="item.Dish?.image_url || '/default-dish.jpg'" class="dish-image">
            <span class="dish-name">{{ item.Dish?.name }}</span>
          </div>
          
          <el-form-item label="评分">
            <el-rate
              v-model="reviewForm.items[index].rating"
              :texts="['很差', '较差', '一般', '不错', '很好']"
              show-text
            />
          </el-form-item>
          
          <el-form-item label="评价内容">
            <el-input
              v-model="reviewForm.items[index].content"
              type="textarea"
              :rows="2"
              placeholder="请输入您的评价内容"
            />
          </el-form-item>
          
          <el-form-item label="上传图片">
            <el-upload
              action="/api/upload"
              list-type="picture-card"
              :headers="{
                Authorization: `Bearer ${store.state.token}`
              }"
              :on-success="(res) => reviewForm.items[index].images.push(res.url)"
              :on-remove="(file) => {
                const imgIndex = reviewForm.items[index].images.indexOf(file.url)
                if (imgIndex !== -1) {
                  reviewForm.items[index].images.splice(imgIndex, 1)
                }
              }"
            >
              <el-icon><Plus /></el-icon>
            </el-upload>
          </el-form-item>
          
          <el-divider v-if="index < currentReviewOrder.Items.length - 1" />
        </div>
      </el-form>
      
      <template #footer>
        <el-button @click="reviewDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitReview">提交评价</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick } from 'vue'
import { useStore } from 'vuex'
import { ElMessage } from 'element-plus'
import dayjs from 'dayjs'

const store = useStore()
const loading = ref(false)
const orders = ref([])
const activeTab = ref('all')
const detailVisible = ref(false)
const currentOrder = ref(null)
const reviewDialogVisible = ref(false)
const currentReviewOrder = ref<any>(null)
const reviewForm = ref({
  orderId: 0,
  items: [] as Array<{
    dishId: number,
    rating: number,
    content: string,
    images: string[]
  }>
})

// 添加分页相关的响应式变量
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 获取订单列表
const loadOrders = async () => {
  loading.value = true
  try {
    const response = await fetch(
      `http://localhost:8080/api/orders?page=${currentPage.value}&pageSize=${pageSize.value}`,
      {
        headers: {
          'Authorization': `Bearer ${store.state.token}`
        }
      }
    )
    const data = await response.json()
    if (response.ok) {
      orders.value = data.orders
      total.value = data.total
    }
  } catch (error) {
    console.error('Load orders error:', error)
    ElMessage.error('加载订单失败')
  } finally {
    loading.value = false
  }
}

// 查看订单详情
const showOrderDetail = async (order) => {
  try {
    const response = await fetch(`http://localhost:8080/api/orders/${order.ID}`, {
      headers: {
        'Authorization': `Bearer ${store.state.token}`
      }
    })
    const data = await response.json()
    if (response.ok) {
      console.log('Order detail:', data.order) // 添加调试日志
      currentOrder.value = data.order
      detailVisible.value = true
    }
  } catch (error) {
    console.error('Load order detail error:', error)
    ElMessage.error('加载订单详情失败')
  }
}

// 打开评价对话框
const showReviewDialog = (order: any) => {
  if (!order || !order.Items?.length) {
    ElMessage.error('订单数据异常')
    return
  }

  console.log('Opening review dialog for order:', order)
  currentReviewOrder.value = order
  
  // 初始化每个菜品的评价表单
  reviewForm.value = {
    orderId: order.ID,
    items: order.Items.map((item: any) => {
      if (!item) return null
      console.log('Initializing review form for dish:', item)
      return {
        dishId: item.DishID,
        rating: 0,
        content: '',
        images: []
      }
    }).filter(Boolean) // 过滤掉 null 值
  }
  
  reviewDialogVisible.value = true
}

// 修改提交评价的方法
const submitReview = async () => {
  if (!currentReviewOrder.value || !reviewForm.value.items.length) {
    ElMessage.error('评价数据异常')
    return
  }
  
  try {
    // 检查评分是否都已填写
    const hasEmptyRating = reviewForm.value.items.some(item => !item || item.rating === 0)
    if (hasEmptyRating) {
      ElMessage.warning('请为所有菜品评分')
      return
    }

    // 检查评价内容是否都已填写
    const hasEmptyContent = reviewForm.value.items.some(item => !item || !item.content.trim())
    if (hasEmptyContent) {
      ElMessage.warning('请为所有菜品填写评价内容')
      return
    }

    // 提交评价的逻辑
    const promises = reviewForm.value.items.map(async (item, index) => {
      if (!item) return null
      
      console.log(`Submitting review for dish ${index + 1}:`, item)
      
      const requestBody = {
        order_id: reviewForm.value.orderId,
        dish_id: item.dishId,
        rating: item.rating,
        content: item.content,
        images: item.images
      }
      console.log('Request body:', requestBody)

      const response = await fetch('http://localhost:8080/api/reviews', {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${store.state.token}`,
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(requestBody)
      })

      console.log(`Response status for dish ${index + 1}:`, response.status)
      const responseText = await response.text()
      console.log(`Response text for dish ${index + 1}:`, responseText)

      if (!response.ok) {
        throw new Error(responseText)
      }

      return JSON.parse(responseText)
    })

    console.log('Submitting all reviews...')
    const results = await Promise.all(promises)
    console.log('All review results:', results)

    // 检查评价是否成功
    if (results.every(result => result && (result.success || result.message))) {
      // 先重置表单和状态
      currentReviewOrder.value = null
      reviewForm.value = {
        orderId: 0,
        items: []
      }
      
      // 关闭对话框
      reviewDialogVisible.value = false
      
      // 显示成功消息
      ElMessage.success('评价成功')
      
      // 刷新订单列表
      await loadOrders()
    } else {
      throw new Error('部分评价提交失败')
    }
  } catch (error) {
    console.error('Review submission error:', error)
    ElMessage.error(error instanceof Error ? error.message : '评价失败')
  }
}

// 格式化日期
const formatDate = (date: string) => {
  return dayjs(date).format('YYYY-MM-DD HH:mm:ss')
}

// 获取状态标签类型
const getStatusType = (status: string) => {
  const types = {
    'pending': 'warning',
    'processing': 'primary',
    'completed': 'success',
    'cancelled': 'info'
  }
  return types[status] || 'info'
}

// 获取状态文本
const getStatusText = (status: string) => {
  const texts = {
    'pending': '待处理',
    'processing': '处理中',
    'completed': '已完成',
    'cancelled': '已取消'
  }
  return texts[status] || status
}

// 处理页码改变
const handleCurrentChange = (val: number) => {
  currentPage.value = val
  loadOrders()
}

// 处理每页条数改变
const handleSizeChange = (val: number) => {
  pageSize.value = val
  currentPage.value = 1 // 重置到第一页
  loadOrders()
}

onMounted(() => {
  loadOrders()
})
</script>

<style scoped>
.orders-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 60px);
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  font-weight: 500;
  color: #303133;
}

.order-card {
  background-color: #fff;
  border-radius: 8px;
}

.order-tabs {
  margin-top: -10px;
}

.order-info-cell {
  padding: 10px 0;
}

.order-items-preview {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.dish-preview-image {
  width: 40px;
  height: 40px;
  object-fit: cover;
  border-radius: 4px;
  margin-right: 8px;
}

.divider {
  margin: 0 8px;
  color: #909399;
}

.order-brief {
  font-size: 13px;
  color: #909399;
}

.order-time {
  margin-right: 15px;
}

.amount {
  color: #f56c6c;
  font-weight: 500;
}

/* 订单详情样式 */
.order-detail-dialog :deep(.el-dialog__body) {
  padding: 0;
}

.order-detail {
  background-color: #fff;
}

.status-banner {
  padding: 20px;
  color: #fff;
  background: linear-gradient(135deg, #409eff 0%, #3a8ee6 100%);
}

.status-banner.completed {
  background: linear-gradient(135deg, #67c23a 0%, #5daf34 100%);
}

.status-banner.cancelled {
  background: linear-gradient(135deg, #909399 0%, #82848a 100%);
}

.status-text {
  font-size: 18px;
  font-weight: 500;
}

.info-row {
  display: flex;
  margin-bottom: 15px;
}

.info-item {
  flex: 1;
  display: flex;
  align-items: center;
}

.info-item.full-width {
  flex: 2;
}

.label {
  color: #909399;
  margin-right: 10px;
  min-width: 70px;
}

.value {
  color: #303133;
}

.detail-table {
  margin: 20px 0;
}

.dish-info {
  display: flex;
  align-items: center;
  padding: 10px 0;
}

.dish-image {
  width: 60px;
  height: 60px;
  object-fit: cover;
  border-radius: 4px;
  margin-right: 15px;
}

.dish-detail {
  flex: 1;
}

.dish-name {
  font-size: 14px;
  color: #303133;
  margin-bottom: 5px;
}

.order-total {
  text-align: right;
  padding: 20px;
  border-top: 1px solid #ebeef5;
  background-color: #fafafa;
}

.total-amount {
  color: #f56c6c;
  font-size: 20px;
  font-weight: bold;
  margin-left: 10px;
}

/* 表格行样式 */
:deep(.el-table .el-table__row) {
  cursor: pointer;
  transition: all 0.3s;
}

:deep(.el-table .el-table__row:hover) {
  background-color: #f5f7fa;
}

.dish-review-item {
  margin-bottom: 20px;
}

.dish-info {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.dish-image {
  width: 50px;
  height: 50px;
  object-fit: cover;
  border-radius: 4px;
  margin-right: 10px;
}

.dish-name {
  font-size: 14px;
  color: #303133;
}

.reviews-section {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #EBEEF5;
}

.section-title {
  margin-bottom: 20px;
}

.section-title h3 {
  font-size: 16px;
  color: #303133;
  margin: 0;
}

.review-item {
  padding: 15px;
  border-bottom: 1px solid #EBEEF5;
}

.review-item:last-child {
  border-bottom: none;
}

.review-content {
  margin-bottom: 15px;
}

.rating-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 10px;
}

.review-time {
  font-size: 12px;
  color: #909399;
}

.review-text {
  margin: 10px 0;
  color: #606266;
  line-height: 1.6;
}

.review-images {
  display: flex;
  gap: 10px;
  margin: 10px 0;
}

.merchant-reply {
  margin-top: 15px;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.merchant-reply h4 {
  font-size: 14px;
  color: #303133;
  margin: 0 0 8px 0;
}

.merchant-reply p {
  color: #606266;
  margin: 0;
  line-height: 1.6;
}

.no-review {
  text-align: center;
  padding: 10px;
  color: #909399;
}

.no-review-section {
  padding: 40px 0;
  text-align: center;
  border-top: 1px solid #EBEEF5;
  margin-top: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style> 